package com.namuan.jp_stock.activity;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import com.namuan.jp_stock.object.Trackback;
import com.namuan.jp_stock.util.ActivityItemAdapter;
import com.namuan.jp_stock.util.AsyncJustplaceRunner;
import com.namuan.jp_stock.util.BaseRequestListener;
import com.namuan.jp_stock.util.Justplace;
import com.namuan.jp_stock.util.JustplaceError;
import com.namuan.jp_stock.util.ObjUtils;
import com.namuan.jp_stock.util.SessionStore;
import com.namuan.jp_stock.util.TrackbackItemAdapter;
import com.namuan.jp_stock.util.Util;
import com.namuan.jp_stock.R;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;

public class TrackbackListActivity extends Activity  implements OnClickListener, OnItemClickListener, OnScrollListener {
    /** Called when the activity is first created. */
	
	private AsyncJustplaceRunner mAsyncRunner;
	private Justplace mJutplace;
	
	
	private Context mContext;
	private ArrayList<Trackback> trackbackItems;
	private ListView trackbackListView;
	private TrackbackItemAdapter ta;
	
	private ImageView navBtn1;
	private ImageView navBtn2;
	private ImageView navBtn3;
	private ImageView navBtn4;
	private int lastindex;
	private boolean lockListView;
	private Boolean loadingMore = false;
	private Boolean isTwoClickBack = false;
	private Boolean isfirst;	
	private TextView tvEndOfList = null;
	private View dummyView;
	private View footerView;
	private View text_end_of_list = null;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.trackbacklist);
        
        lockListView = false;
		isfirst = true;
		mContext = this;
		setContentView(R.layout.main);
		ImageButton headerAddBtn = (ImageButton) findViewById(R.id.headerAddBtn);
      
		TextView userHeaderNickname = (TextView)findViewById(R.id.userHeaderNickname);
		trackbackListView = (ListView)findViewById(R.id.trackbackListView);
		navBtn1 = (ImageView)findViewById(R.id.navBtn1);
		navBtn2 = (ImageView)findViewById(R.id.navBtn2);
		navBtn3 = (ImageView)findViewById(R.id.navBtn3);
		navBtn4 = (ImageView)findViewById(R.id.navBtn4);
		
		headerAddBtn.setOnClickListener(this);		
		userHeaderNickname.setOnClickListener(this);
		
		navBtn1.setOnClickListener(this);
		navBtn2.setOnClickListener(this);
		navBtn3.setOnClickListener(this);
		navBtn4.setOnClickListener(this);
		footerView = ((LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.listfooter, null, false);
		dummyView = ((LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.dummy, null, false);
		
		trackbackListView.addFooterView(dummyView);
		trackbackListView.setOnScrollListener(this);
		trackbackItems = new ArrayList<Trackback>();
		ta = new TrackbackItemAdapter(this, R.layout.trackback_list_row, trackbackItems);
		
		trackbackListView.setAdapter(ta);
		ta.setNotifyOnChange(true);
		
		trackbackListView.setOnItemClickListener(this);
        
        mJutplace = new Justplace();
        mJutplace.setmSession("A03C5AF941BECDD98F5F5903354BFB6C");
		SessionStore.restore(mJutplace, this);
		
		mJutplace.setHeader(userHeaderNickname);
		mAsyncRunner = new AsyncJustplaceRunner(mJutplace);
		init();
		
		
    }
    private void init(){
    	Bundle params = new Bundle();
    	mAsyncRunner.request("trackbacklist.do", params, "GET",
                 new LoadActivityRequestListener(), null);
    	
    	
    }
    
    public class LoadActivityRequestListener extends BaseRequestListener {

		public void onComplete(final String response, final Object state) {
			Log.d("Justplace-Main", "Response: " + response.toString());
			try {
				trackbackItems.clear();
				Log.d("Justplace-Main", "Response: " + response.toString());
				JSONObject json = Util.parseJson(response);
				final ArrayList<Trackback> trackbacks = ObjUtils.jsonToTrackbackList(json.getJSONArray("hashMapList"));
				lastindex = trackbacks.get(trackbacks.size() - 1).getActivityid();
				for (Trackback act : trackbacks) {
					trackbackItems.add(act);
				}
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						while(trackbackItems.size() < 5){
						}
						ta.notifyDataSetChanged();
						isfirst = false;
						if(trackbackItems.size() == 30){
							loadingMore = true;
							trackbackListView.addFooterView(footerView);
						} else {
							loadingMore = false;		
						}
					}
				});
			} catch (JSONException e) {
				Log.w("Justplace-Main", "JSON Error in response");
			} catch (JustplaceError e) {
				Log.w("Justplace-Main", "Justplace Error: " + e.getMessage());
			}
		}
    }
    public class LoadMoreActivityRequestListener extends BaseRequestListener {
        public void onComplete(final String response, final Object state) {
        	 Log.d("Justplace-LoadMore", "Response: " + response.toString());
            try {
                Log.d("Justplace-LoadMore", "Response: " + response.toString());
                JSONObject json = Util.parseJson(response);
                ArrayList<Trackback> trackbacks =ObjUtils.jsonToTrackbackList(json.getJSONArray("hashMapList"));
                lastindex = trackbacks.get(trackbacks.size()-1).getActivityid();
                if(trackbacks.size()<15){
					loadingMore=false;
                	Log.d("nomore","nomore");                	
                	runOnUiThread(new Runnable() {
						@Override
						public void run() {
							trackbackListView.removeFooterView(footerView);
							//footerView.setVisibility(View.GONE);
							if(text_end_of_list == null) {
								text_end_of_list = ((LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.text_end_of_list, null, false);
								trackbackListView.addFooterView(text_end_of_list);
							}
						}
					});
						
                }
                for(Trackback act:trackbacks){
                	trackbackItems.add(act);
                }
               runOnUiThread(new Runnable(){

				@Override
				public void run() {
					 ta.notifyDataSetChanged();
					 lockListView = false;
				}
            	   
               });
                


  
               
            } catch (JSONException e) {
                Log.w("Justplace-Main", "JSON Error in response");
            } catch (JustplaceError e) {
                Log.w("Justplace-Main", "Justplace Error: " + e.getMessage());
            }
        }
    }
   
    
    

	@Override
	public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onScrollStateChanged(AbsListView arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onClick(View v) {
		switch(v.getId())
		{/*
			case R.id.headerAddBtn:
				Intent Insert_intent = new Intent(this, AddTrackback.class);
			    this.startActivity(Insert_intent);
			    overridePendingTransition(R.anim.fade, R.anim.hold);
				break;
			
			*/
		
			/*	
			case R.id.userHeaderNickname:
				Intent userHeaderIdintent = new Intent(this, MyProfileActivity.class);
			    this.startActivity(userHeaderIdintent);
			    overridePendingTransition(R.anim.fade, R.anim.hold);
				break;
				*/
			case R.id.navBtn1://main
				ta.clear();
				ta.notifyDataSetChanged();
				if(text_end_of_list != null) {
					trackbackListView.removeFooterView(text_end_of_list);
					text_end_of_list = null;
				}
				if(footerView.getParent() != null) {
					trackbackListView.removeFooterView(footerView);
				}
				Bundle params = new Bundle();
				mAsyncRunner.request("loadalltrackbacks.do", params, "GET", new LoadActivityRequestListener(), null);
				break;
				/*
			case R.id.navBtn2://search
				//Intent navBtn2intent = new Intent(this, SearchActivity.class);
				Intent navBtn2intent = new Intent(this, SearchActivity.class);
				//navBtn2intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
				this.startActivity(navBtn2intent);
				overridePendingTransition(R.anim.fade, R.anim.hold);
				//finish();
				break;
				
			case R.id.navBtn3://news
				Intent navBtn3intent = new Intent(this, NewsActivity.class);
				//navBtn3intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
				this.startActivity(navBtn3intent);
				overridePendingTransition(R.anim.fade, R.anim.hold);
				//finish();
				break;
				
			case R.id.navBtn4://setting
				//Intent navBtn2intent = new Intent(this, SearchActivity.class);
				Intent navBtn4intent = new Intent(this, MyProfileActivity.class);
				//navBtn4intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
				this.startActivity(navBtn4intent);
				overridePendingTransition(R.anim.fade, R.anim.hold);
				//finish();
				break;
				*/
		}
		
	}
}
